<!--
 * @Author: dumin
 * @Date: 2025-07-30 10:43:26
 * @Description: 大区子账号的编辑
 * @LastEditors: dumin
 * @LastEditTime: 2025-08-01 09:54:10
-->
<template>
  <div class="sub-account-edit">
    <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px">
      <el-form-item label="账号：" prop="userName">
        <el-input v-model="ruleForm.userName"></el-input>
      </el-form-item>
      <el-form-item label="姓名：" prop="realName">
        <el-input v-model="ruleForm.realName"></el-input>
      </el-form-item>
      <el-form-item label="性别：" prop="sex">
        <el-radio v-model="ruleForm.sex" :label="1">男</el-radio>
        <el-radio v-model="ruleForm.sex" :label="2">女</el-radio>
      </el-form-item>
      <el-form-item label="密码：" prop="password" v-if="this.$route.params.flagmi">
        <el-input v-model="ruleForm.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="手机：" prop="tel">
        <el-input v-model="ruleForm.tel" maxlength="11"></el-input>
      </el-form-item>
      <el-form-item label="选择组织：" prop="dangorgname">
        <el-select v-model="ruleForm.dangorgname" style="width: 100%;">
          <el-option v-for="item in RentalPayWay" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <!-- <el-input v-model="ruleForm.dangorgname" disabled></el-input> -->
      </el-form-item>
      <el-form-item label="账号类型" prop="userType">
        <el-select v-model="ruleForm.userType" disabled>
          <el-option label="营销区域业务经理" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-radio v-model="ruleForm.status" label="1">启用</el-radio>
        <el-radio v-model="ruleForm.status" label="0">禁用</el-radio>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleFormRef')" size="mini" v-if="flag3" :loading="loading">保
          存</el-button>
        <el-button @click="resetForm('ruleFormRef')" size="mini" type="primary" v-if="flag3">取 消 / 返 回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { addcount, changecount, queryUserById, getfenrole, rolemanage } from '@/api/platformmanage';
import { getAllBase } from '@/api/addShopapply.js';
export default {
  data() {
    return {
      loading: false,
      flag3: true,
      RentalPayWay: [],
      ruleForm: {
        userId: '',
        dangorgname: '',
        password: '',
        sex: 1,
        userName: '',
        realName: '',
        userType: '3',
        status: '1',
        tel: '',
        orgSeq: '',
        orgList: [],
      },
      rules: {
        userId: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        status: [{ required: true, message: '请输入状态', trigger: 'blur' }],
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[0123456789])\d{8}$/,
            message: '请输入正确的手机号',
            trigger: 'blur',
          },
        ],
        userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择男女', trigger: 'blur' }],
        realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        userType: [
          { required: true, message: '请输入账号类型', trigger: 'change' },
        ],
        dangorgname: [
          { required: true, message: '请选择当前组织', trigger: 'change' },
        ]
      },
      userInfo: {},
      orgSeq: '',
      // 角色列表
      roleReqs: [],
    }
  },
  created() {

    this.flag3 = this.$route.params.flag3;
    const logininfo = localStorage.getItem('logininfo') || '{}';
    this.userInfo = JSON.parse(logininfo);
    this.orgSeq = this.userInfo.orgSeq;

    const v = this.$route.params.edit;
    if (v) {
      this.ruleForm.userId = v.userId;
      this.ruleForm.password = v.password;
      this.ruleForm.userName = v.userName;
      this.ruleForm.sex = v.sex;
      this.ruleForm.realName = v.realName;
      this.ruleForm.tel = v.tel;
      this.ruleForm.orgSeq = v.orgSeq;
      this.ruleForm.userType = String(v.userType);
      this.ruleForm.status = String(v.status);
      this.ruleForm.dangorgname = v.orgSeq;
    } else {
      this.getrolemanage();
    }

    this.selCore(this.orgSeq);
  },
  methods: {
    selCore(value) {
      if (value != '' && value != undefined && value != null) {
        this.orgSeq = value;
        let data = {
          code: value,
        };
        getAllBase(data).then((res) => {
          this.RentalPayWay = res.result;
        });
      } else {
        this.orgSeq = JSON.parse(this.logininfo).orgSeq;
      }
    },
    getrolemanage() {
      rolemanage().then(res => {
        if (res.code == 1) {
          const cur = res.records.find(item => item.roleReq == 'jd_manager')
          this.roleReqs = [cur.roleId]
        }
      })
    },
    // 分配角色
    async sureRole(userId) {
      const data = {
        userId,
        roleReqs: this.roleReqs
      }
      await getfenrole(data).then(res => {
        if (res.code == 1) {
          this.$message({
            showClose: true,
            message: res.message,
            type: 'success',
          });
          this.$router.go(-1);
        }
      })
    },
    submitForm(formName) {
      if (this.$route.params.edit) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.ruleForm.orgSeq = this.$route.params.edit.orgList.length > 0 ? this.$route.params.edit.orgList[0].orgSeq : "";
            const orgName = this.RentalPayWay.find(item => item.id == this.ruleForm.dangorgname)
            if (!orgName) {
              this.$message({
                message: '请选择正确的组织',
                type: 'error'
              })
              return
            }
            const data = {
              ...this.ruleForm,
              dangorgname: [orgName.name],
              orgList: [{ orgSeq: this.ruleForm.dangorgname }],
            }
            this.loading = true;
            changecount(data).then((res) => {
              if (res.code == 0) {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'error',
                });
              } else {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'success',
                });
                this.$router.go(-1);
              }
            }).finally(() => {
              this.loading = false;
            })
          }
        });
      } else {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const orgName = this.RentalPayWay.find(item => item.id == this.ruleForm.dangorgname)
            if (!orgName) {
              this.$message({
                message: '请选择正确的组织',
                type: 'error'
              })
              return
            }
            const data = {
              ...this.ruleForm,
              dangorgname: [orgName.name],
              orgList: [{ orgSeq: this.ruleForm.dangorgname }],
            }
            this.loading = true;
            addcount(data).then(async (res) => {
              if (res.code == 0) {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'error',
                });
              } else {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'success',
                });
                const roleInfo = JSON.parse(res.result || '{}');
                if(roleInfo.userId) {
                  await this.sureRole(roleInfo.userId);
                }
              }
            }).finally(() => {
              this.loading = false;
            })
          }
        });
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.go('-1');
    }
  }
}
</script>
<style lang="scss" scoped>
.sub-account-edit {
  border: 1px solid #ebeef5;
  margin-left: 150px;
  padding: 50px 100px 20px 150px;
  width: 52%;
  position: relative;
}
</style>